<template>
  <div class="resume-container">
    <h2>在线简历修改</h2>
    <form class="resume-form" @submit.prevent="submitForm">
      <div class="form-group">
        <label for="education">学历:</label>
        <input
          id="education"
          v-model="resumeInfo.education"
          type="text"
          class="form-control"
          placeholder="请输入学历"
        />
      </div>

      <div class="form-group">
        <label for="major">专业:</label>
        <input
          id="major"
          v-model="resumeInfo.major"
          type="text"
          class="form-control"
          placeholder="请输入专业"
        />
      </div>

      <div class="form-group">
        <label for="school">学校:</label>
        <input
          id="school"
          v-model="resumeInfo.school"
          type="text"
          class="form-control"
          placeholder="请输入学校"
        />
      </div>

      <div class="form-group">
        <label for="graduationTime">毕业时间:</label>
        <input
          id="graduationTime"
          v-model="resumeInfo.graduationTime"
          type="date"
          class="form-control"
        />
      </div>

      <div class="form-group">
        <label for="workExperience">工作经历:</label>
        <textarea
          id="workExperience"
          v-model="resumeInfo.workExperience"
          class="form-control"
          rows="4"
          placeholder="请输入工作经历"
        ></textarea>
      </div>

      <div class="form-group">
        <label>技能标签 (最多选择5个):</label>
        <div class="tag-selection">
          <div class="tag-category" v-for="(tags, category) in tagList" :key="category">
            <div class="category-title">{{ category }}</div>
            <div class="tag-options">
              <div
                v-for="tag in tags"
                :key="tag"
                class="tag-item"
                :class="{ selected: selectedTags.includes(tag) }"
                @click="toggleTag(tag)"
              >
                {{ tag }}
              </div>
            </div>
          </div>
        </div>
        <div class="selected-tags">
          已选择: {{ selectedTags.join(', ') || '无' }}
        </div>
      </div>

      <div class="form-group">
        <label for="selfEvaluation">自我评价:</label>
        <textarea
          id="selfEvaluation"
          v-model="resumeInfo.selfEvaluation"
          class="form-control"
          rows="4"
          placeholder="请输入自我评价"
        ></textarea>
      </div>

      <!-- 添加简历附件上传 -->
      <div class="form-group">
        <label>简历附件:</label>
        <div class="resume-file-section">
          <div v-if="resumeInfo.resumeFile" class="file-preview">
            <a :href="resumeInfo.resumeFile" target="_blank" class="file-link">
              查看已上传的简历文件
            </a>
          </div>
          <div class="upload-area">
            <input
              ref="fileInput"
              type="file"
              accept=".pdf,.doc,.docx"
              @change="handleFileChange"
              class="file-input"
            />
            <button type="button" @click="triggerFileInput" class="upload-button">
              选择文件
            </button>
            <p class="upload-hint">支持 PDF、DOC、DOCX 格式，大小不超过 5MB</p>
          </div>
        </div>
      </div>

      <div class="form-actions">
        <button type="submit" class="submit-button">保存简历</button>
        <button type="button" @click="goToProfile" class="profile-button">
          返回个人信息
        </button>
      </div>
    </form>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import apiClient from '@/utils/api'
import axios from 'axios'
import { useRouter } from 'vue-router'

export default {
  name: 'UserResume',
  setup () {
    const router = useRouter()
    const fileInput = ref(null)

    const resumeInfo = ref({
      vitaeId: null,
      userId: null,
      education: '',
      major: '',
      school: '',
      graduationTime: '',
      workExperience: '',
      selfEvaluation: '',
      resumeFile: '',
      status: '1'
    })

    const tagList = ref({})
    const selectedTags = ref([])

    const loadTagList = async () => {
      try {
        const response = await apiClient.get('/job/tagList')
        if (response.data.code === '200') {
          tagList.value = response.data.data
        }
      } catch (error) {
        console.error('获取标签列表失败:', error)
        alert('获取技能标签失败: ' + error.message)
      }
    }

    const loadResumeInfo = async () => {
      try {
        const storedUserInfo = JSON.parse(localStorage.getItem('userInfo'))
        if (!storedUserInfo || !storedUserInfo.userId) {
          alert('用户信息不存在，请重新登录')
          return
        }

        resumeInfo.value.userId = storedUserInfo.userId

        const response = await apiClient.get('/user/getUserVitae', {
          params: {
            userId: storedUserInfo.userId
          }
        })

        if (response.data.code === '200' && response.data.data) {
          const data = response.data.data
          resumeInfo.value = {
            ...resumeInfo.value,
            vitaeId: data.vitaeId,
            education: data.education || '',
            major: data.major || '',
            school: data.school || '',
            graduationTime: data.graduationTime || '',
            workExperience: data.workExperience || '',
            selfEvaluation: data.selfEvaluation || '',
            resumeFile: data.resumeFile || '',
            status: data.status || '1'
          }

          // 设置已选择的标签
          selectedTags.value = data.tags || []
        }
      } catch (error) {
        console.error('获取简历信息失败:', error)
        alert('获取简历信息失败: ' + error.message)
      }
    }

    // 处理文件上传
    const handleFileChange = async (event) => {
      const file = event.target.files[0]
      if (!file) return

      // 验证文件类型和大小
      const validTypes = ['application/pdf', 'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document']
      const maxSize = 5 * 1024 * 1024 // 5MB

      if (!validTypes.includes(file.type)) {
        alert('简历文件只能是 PDF、DOC 或 DOCX 格式!')
        return
      }

      if (file.size > maxSize) {
        alert('简历文件大小不能超过 5MB!')
        return
      }

      // 上传文件
      try {
        const formData = new FormData()
        formData.append('file', file)

        // 创建一个新的 axios 实例用于文件上传，避免拦截器修改 Content-Type
        const token = localStorage.getItem('token')
        const uploadClient = axios.create({
          baseURL: 'http://localhost/api'
        })

        // 添加请求拦截器，只添加 token，不修改 Content-Type
        uploadClient.interceptors.request.use(
          config => {
            if (token) {
              config.headers.Token = token
            }
            return config
          },
          error => {
            return Promise.reject(error)
          }
        )

        const response = await uploadClient.post('/candidate/uploadResumeFile', formData)

        if (response.data && response.data.data) {
          resumeInfo.value.resumeFile = response.data.data
          alert('简历文件上传成功')
        } else {
          alert('简历文件上传失败')
        }
      } catch (error) {
        console.error('上传失败:', error)
        alert('简历文件上传失败: ' + error.message)
      }
    }

    const triggerFileInput = () => {
      fileInput.value.click()
    }

    const toggleTag = (tag) => {
      const index = selectedTags.value.indexOf(tag)
      if (index > -1) {
        // 如果已选择，则取消选择
        selectedTags.value.splice(index, 1)
      } else {
        // 如果未选择且未达到上限，则添加
        if (selectedTags.value.length < 5) {
          selectedTags.value.push(tag)
        } else {
          alert('最多只能选择5个技能标签')
        }
      }
    }

    const formatDate = (dateString) => {
      if (!dateString) return ''
      // 如果已经是 YYYY-MM-DD 格式，直接返回
      if (/^\d{4}-\d{2}-\d{2}$/.test(dateString)) {
        return dateString
      }
      // 如果是日期对象或其他格式，转换为 YYYY-MM-DD
      const date = new Date(dateString)
      if (isNaN(date.getTime())) return ''
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }

    const submitForm = async () => {
      try {
        // 确保日期格式正确
        const formattedGraduationTime = formatDate(resumeInfo.value.graduationTime)

        // 构建提交数据，确保所有字段都正确包含
        const submitData = {
          vitaeId: resumeInfo.value.vitaeId,
          userId: resumeInfo.value.userId,
          education: resumeInfo.value.education,
          major: resumeInfo.value.major,
          school: resumeInfo.value.school,
          graduationTime: formattedGraduationTime,
          workExperience: resumeInfo.value.workExperience,
          tags: selectedTags.value,
          selfEvaluation: resumeInfo.value.selfEvaluation,
          resumeFile: resumeInfo.value.resumeFile,
          status: resumeInfo.value.status
        }

        console.log('提交的数据:', submitData)

        // 明确指定 Content-Type 为 application/json
        const response = await apiClient.post('/candidate/updateVitae', submitData, {
          headers: {
            'Content-Type': 'application/json'
          }
        })

        if (response.data.code === '200') {
          alert('简历保存成功')
        } else {
          alert(response.data.message || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        alert('保存失败: ' + error.message)
      }
    }

    const goToProfile = () => {
      router.push('/user/profile')
    }

    onMounted(() => {
      loadTagList()
      loadResumeInfo()
    })

    return {
      resumeInfo,
      tagList,
      selectedTags,
      fileInput,
      toggleTag,
      handleFileChange,
      triggerFileInput,
      submitForm,
      goToProfile
    }
  }
}
</script>

<style scoped>
.resume-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  font-family: 'Arial', sans-serif;
}

h2 {
  color: #1890ff;
  text-align: center;
  margin-bottom: 30px;
  font-size: 24px;
}

.resume-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  font-weight: bold;
  margin-bottom: 8px;
  color: #333;
  font-size: 16px;
}

.form-control {
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-control:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

textarea.form-control {
  resize: vertical;
  min-height: 100px;
}

.tag-selection {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  max-height: 300px;
  overflow-y: auto;
}

.tag-category {
  margin-bottom: 15px;
}

.tag-category:last-child {
  margin-bottom: 0;
}

.category-title {
  font-weight: bold;
  margin-bottom: 10px;
  color: #1890ff;
  padding-bottom: 5px;
  border-bottom: 1px solid #ebeef5;
}

.tag-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tag-item {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.tag-item:hover {
  border-color: #1890ff;
}

.tag-item.selected {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

.selected-tags {
  margin-top: 15px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 14px;
}

/* 简历附件上传样式 */
.resume-file-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}

.file-preview {
  flex: 0 0 auto;
}

.file-link {
  color: #1890ff;
  text-decoration: none;
}

.file-link:hover {
  text-decoration: underline;
}

.upload-area {
  flex: 1;
  min-width: 200px;
}

.file-input {
  display: none;
}

.upload-button {
  padding: 10px 20px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}

.upload-button:hover {
  background-color: #40a9ff;
}

.upload-hint {
  margin-top: 10px;
  font-size: 14px;
  color: #909399;
}

.form-actions {
  display: flex;
  gap: 15px;
  padding-top: 20px;
  margin-top: 20px;
  border-top: 1px solid #ebeef5;
}

.submit-button, .profile-button {
  padding: 12px 30px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.submit-button {
  background-color: #1890ff;
  color: white;
}

.submit-button:hover {
  background-color: #40a9ff;
}

.profile-button {
  background-color: #fff;
  color: #1890ff;
  border: 1px solid #1890ff;
}

.profile-button:hover {
  background-color: #e6f7ff;
}

@media (max-width: 768px) {
  .resume-container {
    margin: 10px;
    padding: 20px;
  }

  .form-actions {
    flex-direction: column;
  }

  .tag-options {
    gap: 8px;
  }

  .tag-item {
    padding: 4px 10px;
    font-size: 13px;
  }

  .resume-file-section {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
